package com.fly.user.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Map;
import java.util.Optional;

/**
 * Created by fly on 2019/9/26.
 */
@Slf4j
public class CustomJwtConverter extends DefaultAccessTokenConverter implements
        JwtAccessTokenConverterConfigurer {
    @Override
    public void configure(JwtAccessTokenConverter converter) {
        converter.setAccessTokenConverter(this);
    }

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        log.info("请求权限认证信息 -> {}", map);
        OAuth2Authentication auth = super.extractAuthentication(map);

        PrincipalUser user = new PrincipalUser();
        Optional.ofNullable(map.get("userId")).ifPresent((value) -> user.setUserId(Long.parseLong(value.toString())));
        auth.setDetails(user);
        return auth;
    }
}
